<?php
/**
 * 用户管理
 * @since   2018-06-11
 * @author  winljm001 <winljm001@126.com>
 */

namespace app\admin\controller;



use app\model\AdminExaminee;
use app\model\AdminAcademicRecords;
use app\model\AdminTestPersonnel;
use app\util\ReturnCode;
use app\util\Tools;

class Examinee extends Base {

    /**
     * 获取考生列表
     * @return array
     * @throws \think\exception\DbException
     * @author  winljm001 <winljm001@126.com>
     */
    public function index() {

        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords', '');
        $sex = $this->request->get('sex', '');
        $ageGt = $this->request->get('ageGt', '0');
        $ageLt = $this->request->get('ageLt', '999');
        $status = $this->request->get('status', '');

        $where = [];
        if ($status === '1' || $status === '0') {
            $where['status'] = $status;
        }
        if ($sex!='') {
            $where['sex'] = $sex;
        }
        $where['age'] = ['between', $ageGt.','.$ageLt];
        if($keywords!=''){
            $where=array_merge($where,['id|name|idcard|phone'=>['like', "%{$keywords}%"]]);
        }

        $listObj = (new AdminExaminee())->where($where)->order('timeAdd DESC')
            ->paginate($limit, false, ['page' => $start])->toArray();
        $listInfo = $listObj['data'];
        return $this->buildSuccess([
            'list'  => $listInfo,
            'count' => $listObj['total']
        ]);
    }
    /**
     * 考场添加考生的用户中心列表
     * @return array
     * @throws \think\exception\DbException
     * @author  winljm001 <winljm001@126.com>
     */
    public function eRoomGetList() {
        $eRoomId = $this->request->get('eRoomId');
        if (!$eRoomId) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords', '');
        $sex = $this->request->get('sex', '');
        $ageGt = $this->request->get('ageGt', '0');
        $ageLt = $this->request->get('ageLt', '999');
        $where = [];
        $where['status'] = 1;
        if ($sex!='') {
            $where['sex'] = $sex;
        }
        $where['age'] = ['between', $ageGt.','.$ageLt];
        if($keywords!=''){
            $where=array_merge($where,['id|name|idcard|phone'=>['like', "%{$keywords}%"]]);
        }
        $listObj = (new AdminExaminee())->where($where)->order('timeAdd DESC')
            ->paginate($limit, false, ['page' => $start])->toArray();
        $listInfo = $listObj['data'];
        $where2= [];
        $where2['examinationRoomId'] = $eRoomId;
        $testPersonnelList=(new AdminTestPersonnel())->where($where2)->select();
        foreach ($listInfo as $k2 => $v2) {
            $listInfo[$k2]['isAddRoom']=0;
        }
        foreach ($testPersonnelList as $k1 => $v1) {
            foreach ($listInfo as $k2 => $v2) {
                if($v1['examineeId']==$v2['Id']){
                    $listInfo[$k2]['isAddRoom']=1;
                }
            }
        }
        // var_dump($testPersonnelList);
        return $this->buildSuccess([
            'list'  => $listInfo,
            'count' => $listObj['total']
        ]);
    }
    /**
     * 考场添加考生的历史记录列表
     * @return array
     * @throws \think\exception\DbException
     * @author  winljm001 <winljm001@126.com>
     */
    public function eHistoryGetList() {
        $eRoomId = $this->request->get('eRoomId');
        if (!$eRoomId) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $testStatus = $this->request->get('testStatus', '');
        $isQualified = $this->request->get('isQualified', '');
        $keywords = $this->request->get('keywords', '');
        $keywords2 = $this->request->get('keywords2', '');
        $gradeGt = $this->request->get('gradeGt', '-9999');
        $gradeLt = $this->request->get('gradeLt', '9999');
        $where = [];
        $where['e.status'] = 1;
        $where['h.grade'] = ['between', $gradeGt.','.$gradeLt];
        if($testStatus!=''){
            if($testStatus==1){
                $testStatusQStr = '((f.examEndTime>="'.time().'") OR (f.examEndTime<"'.time().'" AND h.grade>0))';
            }else{
                $testStatusQStr = '(f.examEndTime<"'.time().'" AND h.grade<0)';
            }
        }else{
            $testStatusQStr='';
        }
        if($isQualified!=''){
            if($isQualified=='合格'){
                $isQualifiedQStr='(h.grade>=g.passScore)';
            }else{
                $isQualifiedQStr='(h.grade<g.passScore)';
            }
        }else{
            $isQualifiedQStr='';
        }
        if($keywords!=''){
            $where=array_merge($where,['e.id|e.name|e.idcard|e.phone'=>['like', "%{$keywords}%"]]);
        }
        if($keywords2!=''){
            $where=array_merge($where,['f.name'=>['like', "%{$keywords2}%"]]);
        }
        $listObj=(new AdminTestPersonnel())->alias('a')
        ->join('admin_examinee e','a.examineeId = e.id')
        ->join('admin_examination_room f','a.examinationRoomId = f.id')
        ->join('admin_test_paper g','f.testPaperId = g.id')
        ->join('admin_academic_records h','h.testPersonnelId = a.id')
        ->field('e.*,f.name as eRoomName,a.id as testPersonnelId,f.examStartTime,f.examEndTime,f.isPigeonhole,g.passScore,h.grade')
        ->where($where)->where($testStatusQStr)->where($isQualifiedQStr)->order('a.updateTime DESC')
        ->paginate($limit, false, ['page' => $start])->toArray();
        $listInfo = $listObj['data'];
        $where2= [];
        $where2['examinationRoomId'] = $eRoomId;
        $testPersonnelList=(new AdminTestPersonnel())->where($where2)->select();
        foreach ($listInfo as $k2 => $v2) {
            $listInfo[$k2]['isAddRoom']=0;
        }
        foreach ($testPersonnelList as $k1 => $v1) {
            foreach ($listInfo as $k2 => $v2) {
                if($v1['examineeId']==$v2['Id']){
                    $listInfo[$k2]['isAddRoom']=1;
                }
            }
        }
        $where3=[];
        foreach ($listInfo as $key => $value) {
            $isUnsetFlag=false;
            $listInfo[$key]['testStatus'] = ($value['examEndTime']<time()&&$listInfo[$key]['grade']==-1)?0:1;
            if($value['examEndTime']<time()){
                $listInfo[$key]['isQualified']=$listInfo[$key]['grade']>=$listInfo[$key]['passScore']?"合格":"不合格";
            }else{
                $listInfo[$key]['isQualified']="考试未开始";
            }
        }
        // var_dump($testPersonnelList);
        return $this->buildSuccess([
            'list'  => $listInfo,
            'count' => $listObj['total']
        ]);
    }

    /**
     * 考场考生列表
     * @return array
     * @throws \think\exception\DbException
     * @author  winljm001 <winljm001@126.com>
     */
    public function eRoomExamineeList() {
        $eRoomId = $this->request->get('eRoomId');
        if (!$eRoomId) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $limit = $this->request->get('size', config('apiAdmin.ADMIN_LIST_DEFAULT'));
        $start = $this->request->get('page', 1);
        $keywords = $this->request->get('keywords', '');
        $sex = $this->request->get('sex', '');
        $ageGt = $this->request->get('ageGt', '0');
        $ageLt = $this->request->get('ageLt', '999');
        $where = [];
        $where['e.status'] = 1;
        $where['a.examinationRoomId'] = $eRoomId;
        if ($sex!='') {
            $where['e.sex'] = $sex;
        }
        $where['e.age'] = ['between', $ageGt.','.$ageLt];
        if($keywords!=''){
            $where=array_merge($where,['e.id|e.name|e.idcard|e.phone'=>['like', "%{$keywords}%"]]);
        }
        $listObj=(new AdminTestPersonnel())->alias('a')
        ->join('admin_examinee e','a.examineeId = e.id')
        ->where($where)->order('timeAdd DESC')
        ->paginate($limit, false, ['page' => $start])->toArray();
        $listInfo = $listObj['data'];
        
        return $this->buildSuccess([
            'list'  => $listInfo,
            'count' => $listObj['total']
        ]);
    }

    /**
     * 新增考生
     * @return array
     * @author  winljm001 <winljm001@126.com>
     */
    public function add() {
        $postData = $this->request->post();
        $postData['timeAdd'] = time();
        $postData['password'] = Tools::userMd5($postData['password']);
        $res = AdminExaminee::create($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 删除考生
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function del() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        AdminExaminee::destroy($id);
        return $this->buildSuccess([]);
    }

    /**
     * 获取考生
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function getDetail() {
        $id = $this->request->get('id');
        if (!$id) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $data = AdminExaminee::get(['id' => $id]);
        unset($data['password']);
        return $this->buildSuccess([
            'examinee'  => $data
        ]);
    }

    /**
     * 获取考生数量
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function getExamineeNum() {
        $num = count((new AdminExaminee())->select());
        return $this->buildSuccess([
            'examineeNum'  => $num
        ]);
    }
    /**
     * 获取今日考生数量
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function getTodayExamineeNum() {
        $t = time();
        $start_time = mktime(0,0,0,date("m",$t),date("d",$t),date("Y",$t));  //当天开始时间
        $end_time = mktime(23,59,59,date("m",$t),date("d",$t),date("Y",$t)); //当天结束时间
        $TimeStr = '((f.examStartTime>="'.$start_time.'") AND (f.examStartTime<="'.$end_time.'"))';
        $num=count((new AdminTestPersonnel())->alias('a')
        ->join('admin_examination_room f','a.examinationRoomId = f.id')
        ->where($TimeStr)->select());
        return $this->buildSuccess([
            'examineeNum'  => $num
        ]);
    }
    /**
     * 获取总考试人次数量
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function getTestPersonnelNum() {
        $num=count((new AdminTestPersonnel())->select());
        return $this->buildSuccess([
            'examineeNum'  => $num
        ]);
    }

    /**
     * 获取考生全部年龄
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function getAllExamineeAge() {
        $arr=(new AdminExaminee())->field('age')->select();
        return $this->buildSuccess([
            'examineeAge'  => $arr
        ]);
    }

    /**
     * 判断考生是否存在
     * @return object
     * @author winljm001 <winljm001@126.com>
     */
    public function isExist() {
        $idcard = $this->request->get('idcard');
        if (!$idcard) {
            return $this->buildFailed(ReturnCode::EMPTY_PARAMS, '缺少必要参数');
        }
        $data = AdminExaminee::get(['idcard' => $idcard]);
        unset($data['password']);
        return $this->buildSuccess([
            'examinee'  => $data
        ]);
    }

    /**
     * 编辑考生
     * @author winljm001 <winljm001@126.com>
     * @return array
     * @throws \think\exception\DbException
     */
    public function edit() {

        $postData = $this->request->post();
        if(isset($postData['password'])){
            $postData['password'] = Tools::userMd5($postData['password']);
        }
        $res = AdminExaminee::update($postData);
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 考生状态编辑
     * @return array
     * @author winljm001 <winljm001@126.com>
     */
    public function changeStatus() {
        $idArr = explode(',',$this->request->get('id'));
        if ($idArr[0]== '') {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '缺少必要参数');
        }
        $status = $this->request->get('status');
        foreach ($idArr as $key => $value) {
            $res = AdminExaminee::update([
                'Id'         => $value,
                'status'     => $status
            ]);
        }
        if ($res === false) {
            return $this->buildFailed(ReturnCode::DB_SAVE_ERROR, '操作失败');
        } else {
            return $this->buildSuccess([]);
        }
    }

    /**
     * 用户登录
     * @return array
     * @throws \think\Exception
     * @throws \think\exception\DbException
     * @author winljm001 <winljm001@126.com>
     */
    public function login() {
        $idcard = $this->request->post('idcard');
        $password = $this->request->post('password');
        if (!$idcard) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少身份证号!');
        }
        if (!$password) {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '缺少密码!');
        } else {
            $password = Tools::userMd5($password);
        }
        $userInfo = AdminExaminee::get(['idcard' => $idcard, 'password' => $password]);
        if (!empty($userInfo)) {
            if ($userInfo['status']) {
                
            } else {
                return $this->buildFailed(ReturnCode::LOGIN_ERROR, '用户已被禁用，请联系管理员');
            }
        } else {
            return $this->buildFailed(ReturnCode::LOGIN_ERROR, '用户名密码不正确');
        }
        $return['id'] = $userInfo['Id'];
        $return['name'] = $userInfo['name'];

        return $this->buildSuccess($return, '登录成功');
    }
}
